<template>
  <div>
    <el-card class="!border-none" shadow="never">
      <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
        <el-form-item label="用户信息">
          <el-input
              class="w-[280px]"
              v-model="queryParams.keyword"
              placeholder="用户编号/昵称/手机号码"
              clearable
              @keyup.enter="resetPage"
          />
        </el-form-item>
        <el-form-item label="注册时间">
          <daterange-picker
              v-model:startTime="queryParams.startTime"
              v-model:endTime="queryParams.endTime"
          />
        </el-form-item>
        <el-form-item label="注册来源">
          <el-select class="w-[280px]" v-model="queryParams.channel">
            <el-option
                v-for="(item, key) in ClientMap"
                :key="key"
                :label="item"
                :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none mt-4" shadow="never">
      <el-button type="primary" @click="showAddDialog" style="margin-bottom: 15px">新增</el-button>
      <el-table size="large" v-loading="pager.loading" :data="pager.lists">
        <el-table-column label="用户编号" prop="sn" min-width="120"/>
        <el-table-column label="头像" min-width="100">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="50"/>
          </template>
        </el-table-column>
        <el-table-column label="昵称" prop="nickname" min-width="100"/>
        <el-table-column label="账号" prop="username" min-width="120"/>
        <el-table-column label="手机号码" prop="mobile" min-width="100"/>
        <el-table-column label="用户组" prop="groupNames" show-tooltip-when-overflow min-width="100" align="center"/>
        <el-table-column label="短信类型" align="center" show-tooltip-when-overflow min-width="100">
          <template #default="{row}">
            {{ row.smsTypes?.map(item => smsTypeMap[item])?.join(', ') }}
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="createTime" min-width="120"/>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button v-perms="['user:detail']" type="primary" link>
              <router-link
                  :to="{
                                    path: getRoutePath('user:detail'),
                                    query: {
                                        id: row.id
                                    }
                                }"
              >
                详情
              </router-link>
            </el-button>
            <!-- <el-button type="primary" link @click="showEditPermissionsDialog(row)">编辑权限</el-button> -->
			<el-button type="primary" link @click="showEditSMSDialog(row)">编辑</el-button>
            <el-button
                type="danger"
                link
                @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end mt-4">
        <pagination v-model="pager" @change="getLists"/>
      </div>
    </el-card>
    <el-dialog v-model="showDialog" title="新增用户" width="500px">
      <el-form label-position="top" :model="newUser" :rules="mobileRules" ref="ruleFormRef">
        <el-form-item label="用户账号" prop="account">
          <el-input v-model="newUser.account"></el-input>
        </el-form-item>
        <el-form-item label="初始密码" prop="password">
          <el-input v-model="newUser.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="newUser.mobile"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="newUser.nickname"></el-input>
        </el-form-item>
        <!--加一个复选框-->
        <!-- <el-form-item label="权限" prop="authoritys">
          <el-select
              v-model="newUser.authoritys"
              :disabled="isRoot"
              multiple
              class="flex-1"
              clearable
              placeholder="请选择权限"
          >
            <el-option
                v-for="(item, index) in optionsData"
                :key="index"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取消</el-button>
        <el-button type="primary" @click="confirmAdd(ruleFormRef)">确定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑权限弹窗 -->
    <!-- <el-dialog v-model="showEditPermissionsDialogVisible" title="编辑权限" width="500px">
      <el-form :model="editPermissionsForm" ref="editPermissionsFormRef">
        <input type="hidden" name="userId" :value="currentUserId.value">
        <el-form-item label="权限" prop="authoritys">
          <el-select v-model="editPermissionsForm.authoritys" multiple class="flex-1" clearable placeholder="请选择权限">
            <el-option v-for="permission in permissionsOptions" :key="permission.value" :label="permission.label"
                       :value="permission.value"/>
          </el-select>
        </el-form-item>
      </el-form> 
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEditPermissions">取消</el-button>
        <el-button type="primary" @click="confirmEditPermissions">确定</el-button>
      </div>
    </el-dialog>-->
	<!-- 编辑短信弹窗 -->
	<el-dialog v-model="showEditSMSDialogVisible" title="编辑" width="500px">
	  <el-form :model="editSMSForm" ref="editSMSFormRef" label-width="100px">
	    <input type="hidden" name="userId" :value="currentUserId.value">
	    <el-form-item label="短信类型" prop="types">
	      <el-select v-model="editSMSForm.types" multiple class="flex-1" clearable placeholder="请选择">
	        <el-option v-for="type in smsTypeOptions" :key="type.value" :label="type.label"
	                   :value="type.value"/>
	      </el-select>
	    </el-form-item>
		<el-form-item label="用户组" prop="groups">
		    <el-select
		v-model="editSMSForm.groups"
				  multiple
				  placeholder="请选择用户组"
				  style="width: 240px"
				  >
					<el-option
		          v-for="group in dictData.groups"
		          :key="group.id"
		          :label="group.name"
		          :value="group.id"
		      ></el-option>
		    </el-select>
		  </el-form-item>
	  </el-form>
	  <div slot="footer" class="dialog-footer" style="float: right;">
	    <el-button @click="cancelEditSMS">取消</el-button>
	    <el-button type="primary" @click="confirmEditSms">确定</el-button>
	  </div>
	</el-dialog>
  </div>
</template>
<script lang="ts" setup name="consumerLists">
import {usePaging} from '@/hooks/usePaging'
import {getRoutePath} from '@/router'
import {getUserList, userRegister, editPermission,userDelete, editSmsAndGroup} from '@/api/consumer'
import {groupAll} from '@/api/usergroup'
import {ClientMap} from '@/enums/appEnums'
import feedback from "@/utils/feedback";
import {ref} from 'vue';

const showEditPermissionsDialogVisible = ref(false);
const showEditSMSDialogVisible = ref(false);
const currentUserId = ref(''); //当前用户id

const editSMSForm = reactive({
  types: [],
  groups: []
});
//选择的权限
const editPermissionsForm = reactive({
  authoritys: []
});
const authorityMap = {
  '1': '查看',
  '2': '控制',
  '3': '参数',
  '4': '上报'
};

const smsTypeMap = {
  '1': '设备故障',
  '2': '设备离线',
  '3': '运维上报',
  '4': '事件上报',
  '5': '设备故障恢复',
  '6': '设备离线恢复',
  '7': '运维上报处理',
  '8': '事件上报处理',
};
const permissionsOptions = [
  {label: '查看', value: '1'},
  {label: '控制', value: '2'},
  {label: '参数', value: '3'},
  {label: '上报', value: '4'}
];

const smsTypeOptions = [
  {label: '设备故障', value: 1},
  {label: '设备离线', value: 2},
  {label: '运维上报', value: 3},
  {label: '事件上报', value: 4},
  {label: '设备故障恢复', value: 5},
  {label: '设备离线恢复', value: 6},
  {label: '运维上报处理', value: 7},
  {label: '事件上报处理', value: 8},
];
//编辑权限按钮
const showEditPermissionsDialog = (row) => {
  console.log(row)
  currentUserId.value = row.id; // 保存当前用户的id编号
  showEditPermissionsDialogVisible.value = true; //控制弹窗
  editPermissionsForm.authoritys = row.authoritys && row.authoritys.split(','); // 初始化权限选项
};
//取消编辑权限按钮
const cancelEditPermissions = () => {
  showEditPermissionsDialogVisible.value = false;
};

//提交确定权限
const confirmEditPermissions = () => {
  let data = {
    id: currentUserId.value,
    authoritys: editPermissionsForm.authoritys
  }
  // 将编辑的权限传回后端进行保存
  editPermission(data)
      .then(response => {
        feedback.msgSuccess('编辑权限成功');
        editPermissionsForm.authoritys = [];
        getLists()
      })
      .catch(error => {
        console.log(error)
        feedback.msgError('编辑权限失败');
      });
  showEditSMSDialogVisible.value = false;
};

const confirmEditSms = () => {
  let data = {
    id: currentUserId.value,
    smsTypes: editSMSForm.types,
	groupIds: editSMSForm.groups
  }
  // 将编辑的权限传回后端进行保存
  editSmsAndGroup(data)
      .then(response => {
        feedback.msgSuccess('编辑成功');
        editSMSForm.types = [];
		editSMSForm.groups = [];
        getLists()
      })
      .catch(error => {
        console.log(error)
        feedback.msgError('编辑失败');
      });
  showEditSMSDialogVisible.value = false;
};

//编辑权限按钮
const showEditSMSDialog = (row) => {
  currentUserId.value = row.id; // 保存当前用户的id编号
  showEditSMSDialogVisible.value = true; //控制弹窗
  editSMSForm.types = row.smsTypes; // 初始化权限选项
  editSMSForm.groups = row.groupIds;
};
//取消编辑权限按钮
const cancelEditSMS = () => {
  showEditSMSDialogVisible.value = false;
};

const ruleFormRef = ref();
const queryParams = reactive({
  keyword: '',
  channel: '',
  startTime: '',
  endTime: ''
})
//固定四个权限
const optionsData = [
  {name: '查看', id: 1},
  {name: '控制', id: 2},
  {name: '参数', id: 3},
  {name: '上报', id: 4}
]

// //存放站点数据
const dictData = reactive({
  groups: []
});

onMounted(async () => {
  dictData.groups = await groupAll();
});

const {pager, getLists, resetPage, resetParams} = usePaging({
  fetchFun: getUserList,
  params: queryParams
})
//控制弹窗显示
const showDialog = ref(false);
const newUser = reactive({
  account: '',
  password: '',
  mobile: '',
  nickname: '',
  authoritys: [],
  smsTypes: []
});
//验证弹窗
const mobileRules = reactive({
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {required: true, pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: '手机号格式有误', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 12, message: '密码必须在6~12个字符内', trigger: 'blur'},
  ],
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {
      required: true,
      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{3,12}$/,
      message: '账号应为3-12位数字或字母组合',
      trigger: 'blur'
    },
  ],
  nickname: {required: true, message: '请输入昵称', trigger: 'blur'},
  authoritys: {required: true, message: '请选择权限', trigger: 'blur'},
});

const showAddDialog = () => {
  showDialog.value = true; //显示
}
const cancelAdd = () => {
  showDialog.value = false;
  // 清空输入框内容
  newUser.account = '';
  newUser.password = '';
  newUser.mobile = '';
}

//新增用户
const confirmAdd = async (formEl: any) => {
  if (!formEl) return
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      //在这里进行新增逻辑的处理
      let date = {
        username: newUser.account,
        password: newUser.password,
        mobile: newUser.mobile,
        nickname: newUser.nickname,
        authoritys: newUser.authoritys
      }
      userRegister(date)
          .then(response => {
            feedback.msgSuccess("新增用户成功")
            getLists()
          })
      // 处理完毕关闭弹框
      showDialog.value = false;
      // 清空输入框内容
      newUser.account = '';
      newUser.password = '';
      newUser.mobile = '';
      newUser.nickname = '';
      newUser.authoritys = []
    } else {
      console.log('error submit!', fields)
      feedback.msgError("请正确填写注册信息")
    }
  })
}
const handleDelete = async (id: number) => {
  await feedback.confirm('确定要删除？')
  await userDelete({ id })
  feedback.msgSuccess('删除成功')
  getLists()
}
onActivated(() => {
  getLists()
})

getLists()
</script>
<style scoped>
	.dialog-footer {
		float: left;
	}
</style>
